#include <boost/shared_ptr.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>   
#include <boost/property_tree/xml_parser.hpp> 
#include "Config.h"
#include "../engine/DebugStream.h"

using namespace std;
namespace bf=boost::filesystem;

#define CONFIG_PREF_NAME "local_pref.xml"
#define CONFIG_TAG_DEVICE_ID "device-id"
#define CONFIG_TAG_ACCOUNT "account"
#define CONFIG_TAG_PASSWORD "password"
#define CONFIG_TAG_FULL_SYNC "full-sync"

namespace Client {
namespace Common {

static boost::shared_ptr<CConfig> sInstance;

CConfig::CConfig()
{
	Load();
}

CConfig& CConfig::GetInstance()
{
	if(!sInstance) sInstance = boost::shared_ptr<CConfig>(new CConfig());
	return *sInstance;
}

void CConfig::Load()
{
	bf::path conf_file = bf::current_path() / CONFIG_PREF_NAME;
	if(!bf::exists(conf_file)) return;

	using boost::property_tree::ptree;  

	try {
		ptree pt;  
		read_xml(conf_file.string(), pt, boost::property_tree::xml_parser::trim_whitespace);

		mDeviceId = pt.get<string>(CONFIG_TAG_DEVICE_ID);
		mAccount = pt.get<string>(CONFIG_TAG_ACCOUNT);
		mPassword = pt.get<string>(CONFIG_TAG_PASSWORD);
		string s = pt.get<string>(CONFIG_TAG_FULL_SYNC);
		mFullSyncCompleted = (s == "true");
	}
	catch(std::exception&) {
	}
}

void CConfig::Save()
{

	using boost::property_tree::ptree;  
    ptree pt;  
  
    pt.put(CONFIG_TAG_DEVICE_ID, mDeviceId);
	pt.put(CONFIG_TAG_ACCOUNT, mAccount);
	pt.put(CONFIG_TAG_PASSWORD, mPassword);
	pt.put(CONFIG_TAG_FULL_SYNC, mFullSyncCompleted ? "true" : "false");

	bf::path conf_file = bf::current_path() / CONFIG_PREF_NAME;

	boost::property_tree::xml_writer_settings<char> settings('\t', 1, "UTF-8");
	write_xml(conf_file.string(), pt, std::locale(), settings);  

}

} // Common
} // Client